<?php

class Agilet_Dispatcher{
	

	/**
	 * Dispatch the request to get content type.
	 */
	public function dispatch() {
		
		$agilet=  Agilet::getInst();
		$request =  $agilet-> getRequest();
		$baseUrl = $request->getBaseUrl();
		
		$uri = $request -> getRequestUri();
		
		$baseUrl =  $request->getBaseUrl();
		$uri = str_replace($baseUrl, '', $uri);
		
		$uri = str_replace($baseUrl, '', $uri);
		$uri =  trim($uri,'/');
		
		$segments = explode('/', $uri);
		$model = Agilet::getModel('Core.Alias');
		
		$prefix =  'public';
		$module = 'core';
		$controller=  'index';
		$action =  'index';
		
		if(count($segments)){
			$prefix =  array_shift($segments);
		}
		
		// dispatch host name
		//$host = $request -> getHttpHost();
		
		$is_dispactched =  false;
		
		// dispatch sub app.
		if($prefix == 'admin' || $prefix == 'public' || $prefix =='widget'){
			$is_dispactched = true;
			
			if(count($segments)){
				$module =  array_shift($segments);
			}
			if(count($segments)){
				$controller =  array_shift($segments);
			}
			if(count($segments)){
				$action =  array_shift($segments);
			}
			
		}else{
			// unshift segment to processor processor.
			array_unshift($segments, $prefix);
			$prefix = 'public';
			$is_dispactched = false;
		}

		if(!$is_dispactched){
			// dispatch admin mode
			foreach($segments as $segment){
				$term =  $model->getByAlias($segment);
				if(is_object($term)){
					$item =  Agilet::getItem($term->gid);
					if(is_object($item)){
						list($module, $controller, $action) = $item->termMached();
						continue;
					}
				}
				break;
			}
		}
		
		$agilet->process($module, $controller, $action,$prefix);
	}
	
}
